// gateway/main.go
package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"net/http/httputil"
	"net/url"
	"time"

	"github.com/hashicorp/consul/api"
)

func main() {
	// 创建HTTP客户端，设置超时
	cleint := &http.Client{Timeout: 10 * time.Second}
	cleint.Timeout = 10 * time.Second

	// 注册路由
	mux := http.NewServeMux()
	mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
		// 从Consul发现用户服务
		targetURL, err := discoverService("user-service")
		if err != nil {
			http.Error(w, "服务不可用", http.StatusServiceUnavailable)
			return
		}

		// 反向代理请求
		proxy := httputil.NewSingleHostReverseProxy(targetURL)
		proxy.ServeHTTP(w, r)
	})

	// 启动网关
	log.Println("API网关已启动，监听端口:8080")
	if err := http.ListenAndServe(":8080", mux); err != nil {
		log.Fatalf("网关启动失败: %v", err)
	}
}

// 从Consul发现服务
func discoverService(serviceName string) (*url.URL, error) {
	config := api.DefaultConfig()
	client, err := api.NewClient(config)
	if err != nil {
		return nil, fmt.Errorf("连接Consul失败: %v", err)
	}

	// 获取健康的服务实例
	services, _, err := client.Health().Service(serviceName, "", true, nil)
	if err != nil {
		return nil, fmt.Errorf("发现服务失败: %v", err)
	}

	if len(services) == 0 {
		return nil, fmt.Errorf("未找到可用的 %s 服务", serviceName)
	}

	// 随机选择一个实例（负载均衡）
	rand.Seed(time.Now().UnixNano())
	selected := services[rand.Intn(len(services))]
	target := fmt.Sprintf("http://%s:%d", selected.Service.Address, selected.Service.Port)

	return url.Parse(target)
}
